<template>
  <div>
    <div class="pubarticle-container">
      <el-card class="pubarticle-content">
        <div class="title-content">
          <input
            class="title"
            maxlength="50"
            placeholder="请输入文章标题(1~100个字)"
            v-model="optionForm.title"
          />
          <div style="margin-left:auto;">{{ optionForm.title.length }}/50</div>
        </div>
        <div>
          <quill-editor
            class="editor"
            v-model="optionForm.content"
            @image-added="uploadImage"
            ref="editor"
            :options="editorOptions"
          ></quill-editor>
        </div>
      </el-card>
      <el-card class="option-container">
        <el-form ref="optionForm" :model="optionForm">
          <el-form-item>
            <div slot="label">
              标签
            </div>
            <el-tag
              :key="tag.id"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.tag_name }}
            </el-tag>
            <el-button
              class="button-new-tag"
              size="small"
              @click="showTagDialog"
            >
              <i class="el-icon-circle-plus-outline"></i>
              添加标签</el-button
            >
          </el-form-item>
          <el-form-item>
            <div slot="label">
              封面
            </div>
            <UploadImage :editUrl="optionForm.img_url" />
          </el-form-item>
          <el-form-item class="option-content">
            <el-button class="CustomBtn" v-if="!isEdit" @click="Publisharticle"
              >发布文章</el-button
            >
            <el-button type="danger" v-else @click="Editarticle" round
              >编辑文章</el-button
            >
            <!-- <el-button @click="CancelUpload" round>取消</el-button> -->
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <TagDialog type="article" :ShowTagDialogVisible="ShowTagDialogVisible" />
  </div>
</template>

<script>
// 引入组件

import { quillEditor, Quill } from 'vue-quill-editor' // 调用富文本编辑器
import { ImageExtend } from 'quill-image-extend-module'
import { TotalTip } from '@/utils/tip'
import { uploadFileToCos, deleteUploadFile } from '@/api/cos'
import ToolTip from '@/components/Tools/ToolTip'

// quill-image-resize-module该插件是用于控制上传的图片的大小
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', ImageExtend)
Quill.register('modules/imageResize', ImageResize)
// 导入 Quill 样式文件（如果需要自定义样式，请忽略此步骤）
import 'quill/dist/quill.snow.css'
// 注册 ImageResize 模块
Quill.register('modules/imageResize', ImageResize)
import TagDialog from '@/components/Article/TagDialog'
import UploadImage from '@/components/Tools/UploadImage'
export default {
  props: {},
  components: {
    quillEditor,
    TagDialog,
    UploadImage,
    ToolTip
  },
  data() {
    return {
      isEdit: false,
      // 动态显示的tag
      dynamicTags: [],
      // 待删除列表
      deleteImgList: [],
      // 是否成功发布标志位
      PublishSuccess: false,
      // 选项
      optionForm: {
        content:
          '请开始创作<br>规范:<br>所有字体———黑体<br>标题大小————16px<br>正文大小————14px<br>正常颜色————黑色<br>强调颜色————不超过三种',
        title: '',
        referenced_urls: []
      },
      TotalTip: {},
      ShowTagDialogVisible: false,
      // 富文本选项
      editorOptions: {
        modules: {
          toolbar: [
            [{ list: 'ordered' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }],
            [{ size: ['small'] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }],
            [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['link', 'image']
          ],
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        },
        theme: 'snow'
      },
      imgList: []
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    // 获取文章提示
    console.log('quill', this.$refs.editor.quill)
    this.$nextTick(() => {
      this.TotalTip = TotalTip

      // 绑定上传图片事件
      this.$refs.editor.quill
        .getModule('toolbar')
        .addHandler('image', this.uploadImage)
      // 监听封面上传事件
      this.$bus.$on('UploadSuccess', this.getUploadImageUrl)
      this.$bus.$on('RemoveUploadImage', this.RemoveUploadImage)
      // 判断是否为编辑
      this.WhetherEdit()
    })
  },
  beforeDestroy() {
    // 销毁绑定事件
    this.$bus.$off('getTagsId', this.getTagList)
    this.$bus.$off('RemoveUploadImage', this.RemoveUploadImage)
    // 如果没有上传成功
    this.CancelUpload()
  },
  methods: {
    // 发布文章
    async Publisharticle() {
      if (this.optionForm.img_url)
        this.optionForm.referenced_urls.push(this.optionForm.img_url)
      let datas = this.$qs.stringify(this.optionForm, {
        arrayFormat: 'brackets'
      })
      const res = await this.$API.article.publishArticle(datas)
      // 发布成功
      if (res.status == 200) {
        // 标志上传成功
        this.PublishSuccess = true
        this.$message.success('发布成功')
        this.$router.push('/article')
        // window.location.reload();
      } else {
        this.$message.error('发布失败')
      }
    },
    // 上传图片删除事件
    RemoveUploadImage(url) {
      // 清空url
      this.optionForm.img_url = ''
      this.deleteImgList.push(url)
    },
    // 编辑文章
    async Editarticle() {
      if (this.optionForm.img_url)
        this.optionForm.referenced_urls.push(this.optionForm.img_url)

      let datas = this.$qs.stringify(this.optionForm, {
        arrayFormat: 'brackets'
      })
      const res = await this.$API.article.editArticle(datas)
      // 发布成功
      if (res.status == 200) {
        this.$message.success('发布成功')
        this.$router.replace('/article')
        // window.location.reload();
      } else {
        this.$message.error('发布失败')
      }
    },
    // 上传成功回调
    getUploadImageUrl(imgUrl) {
      this.optionForm.img_url = imgUrl
      // 将上传成功的图片存储待删除列表
    },
    // 删除tag
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      let tagList = this.optionForm.tag_ids.split(',')
      console.log(tag)
      this.optionForm.tag_ids = tagList
        .filter(t => {
          return tag.id != t
        })
        .join(',')
    },
    // 打开添加标签对话框
    showTagDialog() {
      this.ShowTagDialogVisible = !this.ShowTagDialogVisible
      // 监听获得tags_id事件
      this.$bus.$on('getTagsId', this.getTagList)
    },
    // 获取tag列表
    getTagList(item) {
      this.optionForm.tag_ids = item.tags_id
      // 重置数组
      this.dynamicTags = []
      let tagList = []
      item.tagList.forEach(tag => {
        tagList.push(tag)
      })
      this.dynamicTags.push(...tagList)
    },
    // 文件上传
    uploadImage() {
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.setAttribute('accept', 'image/*')
      input.click()
      input.onchange = async () => {
        const file = input.files[0]
        // cos存储
        try {
          const res = await uploadFileToCos(file, file.name)
          console.log(res)
          if (res.statusCode == 200) {
            const imageUrl = 'http://' + res.Location
            this.optionForm.referenced_urls.push(imageUrl)
            const range = this.$refs.editor.quill.getSelection(true)
            this.$refs.editor.quill.insertEmbed(range.index, 'image', imageUrl)
            this.deleteImgList.push(imageUrl)
          }
          this.$refs.editor.quill.off('text-change', this.handleImageUpload)
        } catch (error) {}
        // 本地存储
        // const formData = new FormData();
        // formData.append('img', file);
        // try {
        //   const res = await this.$API.article.uploadImage(formData)
        //   console.log(res)
        //   if (res.status == 200) {
        //     const imageUrl = res.data.url;
        //     const range = this.$refs.editor.quill.getSelection(true);
        //     this.$refs.editor.quill.insertEmbed(range.index, 'image', imageUrl);
        //     this.deleteImgList.push(imageUrl);
        //   }
        //   this.$refs.editor.quill.off('text-change', this.handleImageUpload);
        // } catch (error) {
        //   this.$message.error("上传图片失败")
        //   console.error('Image upload failed:', error);
        // }
      }
    },
    // 取消上传
    CancelUpload() {},
    // 判断是否是编辑文章
    WhetherEdit() {
      let isEdit = this.$route.query.isEdit
      let article_id = this.$route.query.id
      console.log(this.$route.query)
      // 如果不是edit就结束
      if (!isEdit || !article_id) return
      this.isEdit = isEdit
      this.getEditarticle(article_id)
    },
    // 获取文章列表
    async getEditarticle(article_id) {
      const res = await this.$API.article.getArticleById(article_id)
      if (res.status == 200) {
        // 获取tag列表
        this.getarticleTagList(article_id, res.data)
      }
    },
    // 获取文章tag列表
    async getarticleTagList(article_id, datas) {
      const res = await this.$API.tags.getArticleTags(article_id)
      if (res.status == 200) {
        let tag_ids = []
        // 动态显示tag
        res.data.forEach(tag => {
          tag_ids.push(tag.id)
          this.dynamicTags.push(tag)
        })
        this.optionForm.tag_ids = tag_ids.join(',')
        // 整理参数
        this.optionForm.article_id = article_id
        this.optionForm.title = datas.info.article_title
        this.optionForm.content = datas.content
        this.optionForm.article_id = datas.info.id
        this.optionForm.img_url = datas.info.img_url
      }
    }
  }
}
</script>

<style scope>
.pubarticle-container {
  width: 80%;
  margin: 20px auto;
}
.pubarticle-content {
  width: 100%;
  /* min-height: 70vh; */
  margin: 20px auto;
}
.title-content {
  width: 100%;
  margin: 0 0 20px 0;
  display: flex;
}
.title {
  display: inline-block;
  width: 100%;
  font-size: 20px;
  color: #606266;
  font-weight: bold;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  /* margin-left: 10px; */
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.ql-editor {
  min-height: 50vh;
}
.option-content {
  margin-top: 50px;
}
.label {
  float: left;
}
</style>
